var express = require('express');
var router = express.Router();
const connection = require('../db/sql');
const utils = require('../utils');
const state = require('../utils/state');
const eventChennel=require('../utils/eventChannel');

/*
移动端注册登录
*/
router.post('/login', async function (req, res, next) {
  // console.log(req.body);
  const { userName, password } = req.body;

  // 1.查看mysql数据库中是否已经存在该用户
  let results = await connection.query(`select * from user where userName='${userName}' and password='${password}'`);
  // 2.判断用户是否存在
  if (!results[0].length) {
    // 用户不存在，注册用户信息
    const userId = utils.randomNumber();
    await connection.query(`insert into user (userId,userName,password) values ('${userId}','${userName}','${password}')`);
  }
  // 3.获取用户信息
  let result = await connection.query(`select * from user where userName='${userName}'`);
  // 4.返回信息到移动端
  res.send({
    state: 200,
    data: result[0][0]
  })
});

/**
 * 用户已扫码但是未确认，这个接口只是为了通知web端，用户当前的进展状态
 */
router.post('/SweepStatus', async (req, res, next) => {
  let uuid = req.body.uuid;
  // 通知web端已扫码
  eventChennel.io.sockets.emit("ScanCodeing", uuid);
  res.json({ status: 200, msg: '发送成功', data: null })
});
/**
 * 移动端App确认登录按钮点击时候的ajax处理
 */
router.post('/scanQRcodeLogin', async (req, res, next) => {
  let uuid = req.body.uuid; // uuid
  let userId = req.body.userId;   // 用户id

  let RedisUidValue = state.get(uuid);
  if (RedisUidValue == null || RedisUidValue == undefined) {
    res.json({
      status: 404,
      msg: '二维码失效或不存在',
      data: null
    });
  } else {
    if (RedisUidValue.length !== 0) {
      res.json({
        status: 404,
        msg: '已登录，请勿重复扫码',
        data: null
      });
    } else {
      // 查询用户信息
      let user = await connection.query(`select * from user where userId='${userId}'`);
      // 保存用户数据到对应key的redis中
      state.set(uuid, JSON.stringify(user[0][0]));
      res.json({
        status: 200,
        msg: '扫码成功',
        data: null
      });
    }
  }

});

module.exports = router;
